// pages/goods/goods.js
let listBehavior = require('../../behavior/list')
Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {

    tableid: 'goods', //模块id
    tableName: '商品定义',  //模块名

    list:[],  //显示数据

    fieldList: [], //所有字段列表

    displayField: [
       {field: 'goods_type;value', title: '商品类别'}
      , {field: 'goods_model;value', title: '规格型号'}
      , {field: 'goods_brand;value', title: '品牌'}
      , {field: 'goods_place;value', title: '产地'}
      , {field: 'goods_unit;value', title: '单位'}
      ],  //显示字段列表

    keyList: [
      {field_id: 'goods_id',field_name: '商品编码'},
      {field_id: 'goods_name',field_name: '商品名称'},
    ],  //搜索关键字
    searchList: [], //快速查询字段列表
    advList: [],  //高级查询列表
    where: [],

    sumList: [] //底部统计字段集合
  },

  getDataList(){
    let url = 'DynamicQuery/query_dynamic_v3',
      {tableid,where,page,limit} = this.data,
      post = {"table_id": tableid,"oby": tableid + ".row_id desc","page":page,"limit": limit};
    this.data.searchWhere = where;
    if (where && where[0]){
      post.SearchWhere = {filters: where ,type: 'and'};
    }
    wx.$post(3,url,post).then(res => {

      let total = 0,
        list = this.data.list,
        sumArr = [],
        obj = {};
      if (res.data.row){
        total = res.data.total;
        let rows = res.data.row;
        if(page !== 1) rows = [ ...list,...rows, ];
        obj = {total,list: rows,page};
      }
      sumArr.push({name: '记录数',num: total});
      if (res.data.sum && res.data.sum[0]) {
        wx.$each(res.data.sum[0],(key,val)=>{
          sumArr.push({name: key,num: wx.$util.formatNum(val)});
        })
      }
      obj.sumList = sumArr;
      this.setData(obj);

    });
  },

  //搜索
  searchData(e){
    this.data.where = e.detail;
    this.getFirstPage();
  },

  //刷新
  refreshData(rid,index){
    if (!rid){
      this.getFirstPage();
      return
    }
    let {tableid,list} = this.data,
      post = {"table_id": tableid,"oby": tableid + ".row_id desc","page":1,"limit": 1,SearchWhere:{
        filters:[{
          CompareValue: rid +'',
          CompareWith: "goods.row_id",
          Operator: "=",
          or: 0
        }],
          type: "and"}};
    wx.$post(3,'DynamicQuery/query_dynamic_v3',post).then(res=>{
      if (res.data.row){
        let data = res.data.row[0];
        list[index] = data;
        this.setData({
          list
        })
      }
    })
  },


  //删除
  bindDelete(e){
    let data = e.currentTarget.dataset,
      rid = data.rid,
      index = data.index;
    wx.showModal({
      title: '提示',
      content: '确认删除该记录？',
      success: (res) => {
        if(res.confirm) {
          wx.showLoading({mask: true})
          wx.$post(3,'DynamicUpdate/dynamic_delete',{row_ids: rid.toString(),table_id: this.data.tableid}).then(res=>{
            if (res.errcode != 0)return;
            let list = this.data.list;
            list.splice(index, 1);
            wx.$toast('删除成功！');
            this.setData({
              list
            });
          })

        }
      },
    })
  },
  //跳转页面
  navTo(e){
    let {url,type} = e.currentTarget.dataset;
    if (type === 'add' && !this.checkAuth('tableAppend')) return;
    if (type === 'edit' && !this.checkAuth('tableEdit')) return;
    wx.navigateTo({
      url: url
    })
  },

  toggleUsed(e) {
    let detail = e.detail,
      dataset = e.currentTarget.dataset,
      index = dataset.index,
      rid = dataset.rid;
    this.setIsUsed(rid,detail).then(()=>{
      let {list} = this.data;
      list[index].is_used = detail;
      // 需要手动对 checked 状态进行更新
      this.setData({ list});
    })
  },
  //设置启用禁用
  setIsUsed(id, isused) {
    if (!this.checkAuth('tableEdit')) return;
    let This = this,
      obj = { row_id: id, is_used: isused },
      post = { "table": { "table_id": "goods", "entitys": [{ "entity": obj, "details": [] }] } };
    return new Promise(resolve => {
      wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(res=>{
        resolve()
      });
    })
  },
  checkAuth(type){
    let flag = false,
      obj = {
        tableAppend: '抱歉，您没有权限新增该模块数据！',
        tableEdit: '抱歉，您没有权限编辑该模块数据！',
        tableDelete: '抱歉，您没有权限删除该模块数据！',
      };
    flag = this.data.auth[type];
    if (!flag){
      wx.$toast(obj[type]);
    }
    return flag;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    wx.$getAuth('goods').then(res=>{
      if (!res.tableSee) {
        wx.$toast('抱歉，您没有权限查看该模块数据！',1000).then(()=>{
          wx.navigateBack({ delta:1 });
        });
        return
      }
      this.setData({
        auth: res
      });
      this.getDataList();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
